package com.freecat.xmqgct.utils;

import android.annotation.SuppressLint;
import android.app.AppOpsManager;
import android.app.DownloadManager;
import android.content.ActivityNotFoundException;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.res.AssetManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.location.LocationManager;
import android.media.MediaMetadataRetriever;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.provider.Settings;
import android.support.v7.app.AlertDialog;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.SPUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.freecat.xmqgct.R;
import com.freecat.xmqgct.mvp.model.api.Api;
import com.lxj.xpopup.XPopup;
import com.taopao.rxdatepicker.widget.RxDatePicker;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.URLEncoder;
import java.security.KeyFactory;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.UUID;


import javax.crypto.Cipher;

/**
 * Created by 12985 on 2017/4/9.
 */

public class Tools {

    //    /**
//     * 初始化图片加载效果
//     */
//    public static RequestBuilder<Drawable> getBitmapRequestBuilder(Context context){
//        return ImageUtils.get().newBitmapBuilder(context).animate(new ViewPropertyAnimation.Animator(){
//            @Override
//            public void animate(View view){
//                AlphaAnimation anim = new AlphaAnimation(0,1);
//                anim.setDuration(150);
//                view.startAnimation(anim);
//            }
//        });
//    }
    private static final String CHECK_OP_NO_THROW = "checkOpNoThrow";
    private static final String OP_POST_NOTIFICATION = "OP_POST_NOTIFICATION";

    private static final double EARTH_RADIUS = 6378137.0;

    public static boolean isVerify() {
        /*
        * 判断是已经验证过5次，如果验证已经5次验证不通过，那么就直接不再跳出
        * */
//            String face_error_log_count = SPUtils.getInstance(Constant.SP_CONFIG).getString(Constant.face_error_log_count);
////
////                if (!face_error_log_count.equals("5")){
////
////                }else {
////
////                    return true;
////                }

            SPUtils spUtils = SPUtils.getInstance(Constant.SP_CONFIG);
            boolean b = spUtils.getBoolean(Constant.MUST_VERIFY);
            double probability = Double.parseDouble(spUtils.getString(Constant.RLSBSJCS));
            if (b) {

                return true;
            } else {
                double d = Math.random();//生成一个0~1的随机数
                return d <= probability;
            }


    }

    /**
     * 加密方式，标准jdk的
     */
    public static final String TRANSFORMATION = "RSA";

    /**
     * 使用公钥加密
     */
    public static byte[] encryptByPublicKey(byte[] data, byte[] publicKey) throws Exception {
        // 得到公钥对象
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKey);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PublicKey pubKey = keyFactory.generatePublic(keySpec);
        // 加密数据
        Cipher cp = Cipher.getInstance(TRANSFORMATION);
        cp.init(Cipher.ENCRYPT_MODE, pubKey);
        return cp.doFinal(data);
    }


//    public static File createWaterMask(String filepathdir,String xmbh, String ZKNumber, String type, File src, Context context) {
//        View view = LayoutInflater.from(context).inflate(R.layout.water_layout, null);
//        TextView tv_xm_num = view.findViewById(R.id.tv_xm_num);
//        TextView tvNum = view.findViewById(R.id.tv_zk_num);
//        TextView tvType = view.findViewById(R.id.tv_type);
//        TextView tvTime = view.findViewById(R.id.tv_time);
//        tv_xm_num.setText(xmbh);
//        if (ZKNumber!=null){
//            tvNum.setText(ZKNumber);
//        }else {
//            tvNum.setText("");
//        }
//        tvType.setText(type);
//        String time = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss", Locale.CHINA).format(new Date());
//        String time1 = new SimpleDateFormat("yyyyMMddHHmmss", Locale.CHINA).format(new Date());
//        tvTime.setText(time);
//        Bitmap bitmap = convertViewToBitmap(view);
//        Bitmap srcBit = BitmapFactory.decodeFile(src.getAbsolutePath());
//        Bitmap waterMaskBitmap = createWaterMaskBitmap(srcBit, bitmap);
////        String path = Environment.getExternalStorageDirectory().getPath();
//        //照片保存路径
//        String fileName = ZKNumber + "-" + type + "-" + time1;
//
//        String filepath = filepathdir+"/" + fileName + ".jpg";
//        System.out.println("filepath============================"+filepath);
//
//        File file = new File(filepath);
//        BufferedOutputStream bos = null;
//        try {
//            bos = new BufferedOutputStream(new FileOutputStream(file));
//            waterMaskBitmap.compress(Bitmap.CompressFormat.JPEG, 50, bos);//将图片压缩的流里面
//            bos.flush();// 刷新此缓冲区的输出流
//            bos.close();// 关闭此输出流并释放与此流有关的所有系统资源
//            bitmap.recycle();//回收bitmap空间
//            waterMaskBitmap.recycle();//回收bitmap空间
//            bitmap.recycle();//回收bitmap空间
//            System.out.println("照片名称和路径"+file.toURI().toURL().toString());
//            return file;
//        } catch (Exception e) {
//            e.printStackTrace();
//            return src;
//        }
//    }


    public static File createWaterMask(String xmbh, String ZKNumber, String type, File src, Context context) {
        View view = LayoutInflater.from(context).inflate(R.layout.water_layout, null);
        TextView tv_xm_num = view.findViewById(R.id.tv_xm_num);
        TextView tvNum = view.findViewById(R.id.tv_zk_num);
        TextView tvType = view.findViewById(R.id.tv_type);
        TextView tvTime = view.findViewById(R.id.tv_time);
        tv_xm_num.setText(xmbh);
        if (ZKNumber!=null){
            tvNum.setText(ZKNumber);
        }else {
            tvNum.setText("");
        }
        tvType.setText(type);
        String time = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss", Locale.CHINA).format(new Date());
        String time1 = new SimpleDateFormat("yyyyMMddHHmmss", Locale.CHINA).format(new Date());
        tvTime.setText(time);
        Bitmap bitmap = convertViewToBitmap(view);
        Bitmap srcBit = BitmapFactory.decodeFile(src.getAbsolutePath());
        Bitmap waterMaskBitmap = createWaterMaskBitmap(srcBit, bitmap);
        String path = Environment.getExternalStorageDirectory().getPath();
        //照片保存路径
        String fileName = ZKNumber + "-" + type + "-" + time1;


        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);
        String mainfilepath="nanjiang";
        String datapath=String.valueOf(year);
        String projectpath="project";

        String filepath = path + "/"+mainfilepath+ "/"+ datapath+ "/"+ projectpath+ "/"+xmbh+"/" + fileName + ".jpg";
        File file = new File(filepath);
        BufferedOutputStream bos = null;
        try {
            bos = new BufferedOutputStream(new FileOutputStream(file));
            waterMaskBitmap.compress(Bitmap.CompressFormat.JPEG, 50, bos);//将图片压缩的流里面
            bos.flush();// 刷新此缓冲区的输出流
            bos.close();// 关闭此输出流并释放与此流有关的所有系统资源
            bitmap.recycle();//回收bitmap空间
            waterMaskBitmap.recycle();//回收bitmap空间
            bitmap.recycle();//回收bitmap空间
            System.out.println("照片名称和路径"+file.toURI().toURL().toString());
            return file;
        } catch (Exception e) {
            e.printStackTrace();
            return src;
        }
    }

    /*
    *
    * */
    public static File createWaterMask(File src, Context context) {
        View view = LayoutInflater.from(context).inflate(R.layout.water_layout, null);
        TextView tv_xm_num = view.findViewById(R.id.tv_xm_num);
        TextView tvNum = view.findViewById(R.id.tv_zk_num);
        TextView tvType = view.findViewById(R.id.tv_type);
        TextView tvTime = view.findViewById(R.id.tv_time);
//        tv_xm_num.setText(xmbh);
//        if (ZKNumber!=null){
//            tvNum.setText(ZKNumber);
//        }else {
//            tvNum.setText("");
//        }
//        tvType.setText(type);
        String time = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss", Locale.CHINA).format(new Date());
        String time1 = new SimpleDateFormat("yyyyMMddHHmmss", Locale.CHINA).format(new Date());
        tvTime.setText(time);
        Bitmap bitmap = convertViewToBitmap(view);
        Bitmap srcBit = BitmapFactory.decodeFile(src.getAbsolutePath());
        Bitmap waterMaskBitmap = createWaterMaskBitmap(srcBit, bitmap);
        String path = Environment.getExternalStorageDirectory().getPath();
        //照片保存路径
//        String fileName = ZKNumber + "-" + type + "-" + time1;
        String fileName = time1;
        String filepath = path + "/" + fileName + ".jpg";
        File file = new File(filepath);
        BufferedOutputStream bos = null;
        try {
            bos = new BufferedOutputStream(new FileOutputStream(file));
            waterMaskBitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);//将图片压缩的流里面
            bos.flush();// 刷新此缓冲区的输出流
            bos.close();// 关闭此输出流并释放与此流有关的所有系统资源
            bitmap.recycle();//回收bitmap空间
            waterMaskBitmap.recycle();//回收bitmap空间
            bitmap.recycle();//回收bitmap空间
            System.out.println("照片名称和路径"+file.toURI().toURL().toString());
            return file;
        } catch (Exception e) {
            e.printStackTrace();
            return src;
        }
    }


    private static Bitmap createWaterMaskBitmap(Bitmap src, Bitmap watermark) {
        if (src == null) {
            return null;
        }
        int width = src.getWidth();
        int height = src.getHeight();
        //创建一个bitmap
        Bitmap newb = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);// 创建一个新的和SRC长度宽度一样的位图
        //将该图片作为画布
        Canvas canvas = new Canvas(newb);
        //在画布 0，0坐标上开始绘制原始图片
        canvas.drawBitmap(src, 0, 0, null);
        //在画布上绘制水印图片
        int height1 = watermark.getHeight();
        canvas.drawBitmap(watermark, 20, height - height1 - 30, null);
        // 保存
        canvas.save();
        // 存储
        canvas.restore();
        return newb;
    }

    private static Bitmap convertViewToBitmap(View view) {
        view.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
        view.buildDrawingCache();
        return view.getDrawingCache();
    }

    public static double getDistance(double longitude1, double latitude1,
                                     double longitude2, double latitude2) {
        double Lat1 = rad(latitude1);
        double Lat2 = rad(latitude2);
        double a = Lat1 - Lat2;
        double b = rad(longitude1) - rad(longitude2);
        double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2)
                + Math.cos(Lat1) * Math.cos(Lat2)
                * Math.pow(Math.sin(b / 2), 2)));
        s = s * EARTH_RADIUS;
        s = Math.round(s * 10000) / 10000;
        return s;
    }

    private static double rad(double d) {
        return d * Math.PI / 180.0;
    }


    /**
     * 选择时间
     *
     * @param context
     * @param textView 显示的位置
     * @param mNow     当前时间（yyyy-MM-dd HH:mm）
     */
    public static void selectTime(Context context, TextView textView, String mNow) {
        RxDatePicker mRxDatePicker1 = new RxDatePicker(context, new RxDatePicker.ResultHandler() {
            @Override
            public void handle(String time) { // 回调接口，获得选中的时间
                textView.setText(time);
            }
        }, "2010-01-01 00:00:00", "2030-01-01 00:00:00"); // 初始化日期格式请用：yyyy-MM-dd HH:mm，否则不能正常运行
        mRxDatePicker1.showSpecificTime(true); // 不显示时和分
        mRxDatePicker1.setIsLoop(false); // 不允许循环滚动
        mRxDatePicker1.show(mNow);
    }

    @SuppressLint("NewApi")
    public static boolean isNotificationEnabled(Context context) {

        AppOpsManager mAppOps =
                (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);

        ApplicationInfo appInfo = context.getApplicationInfo();
        String pkg = context.getApplicationContext().getPackageName();
        int uid = appInfo.uid;
        Class appOpsClass = null;

        /* Context.APP_OPS_MANAGER */
        try {
            appOpsClass = Class.forName(AppOpsManager.class.getName());

            Method checkOpNoThrowMethod =
                    appOpsClass.getMethod(CHECK_OP_NO_THROW,
                            Integer.TYPE, Integer.TYPE, String.class);

            Field opPostNotificationValue = appOpsClass.getDeclaredField(OP_POST_NOTIFICATION);
            int value = (Integer) opPostNotificationValue.get(Integer.class);

            return ((Integer) checkOpNoThrowMethod.invoke(mAppOps, value, uid, pkg) ==
                    AppOpsManager.MODE_ALLOWED);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }


    public static void loadImage(Context context, String id, ImageView imageView) {
        if (TextUtils.isEmpty(id)) return;
        String url;
        if (!id.contains("storage")) {
            url = Api.FILE_DOMAIN + URLEncoder.encode(id);
        } else {
            url = id;
        }
        RequestOptions options = new RequestOptions()
//                .skipMemoryCache(true)
                .placeholder(R.drawable.icon_erro)
                .error(R.drawable.icon_erro);
        Glide.with(context.getApplicationContext()).applyDefaultRequestOptions(options).load(url).into(imageView);
    }

    public static void enlargePhoto(Context context, String id, ImageView imageView) {
        if (TextUtils.isEmpty(id)) return;
        String url;
        if (!id.contains("storage")) {
            url = Api.FILE_DOMAIN + URLEncoder.encode(id);
        } else {
            url = id;
        }
        new XPopup.Builder(context).asImageViewer(imageView, url, new ImageLoader()).show();
    }

    public static void showLocServiceDialog(final Context context) {
        new AlertDialog.Builder(context).setTitle("手机未开启位置服务")
                .setMessage("请再设置中将位置服务打开")
                .setNegativeButton("取消", null)
                .setPositiveButton("去设置", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Intent intent = new Intent();
                        intent.setAction(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        try {
                            context.startActivity(intent);
                        } catch (ActivityNotFoundException ex) {
                            intent.setAction(Settings.ACTION_SETTINGS);
                            try {
                                context.startActivity(intent);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }
                })
                .show();
    }

    public static boolean isLocServiceEnable(Context context) {
        LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        boolean gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        boolean network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        return gps || network;
    }

//    public static void downLoadApk(Context context, String url) {
//        DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
//        Uri uri = Uri.parse(url);
//        DownloadManager.Request request = new DownloadManager.Request(uri);
//        request.setTitle(AppUtils.getAppName());
//        request.setDescription("版本更新");
//        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
//        request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE | DownloadManager.Request.NETWORK_WIFI);
//        request.setVisibleInDownloadsUi(true);
//        request.setDestinationInExternalFilesDir(context, null, "projectSurvey.apk");
//        long id = downloadManager.enqueue(request);
//        SPUtils.getInstance(Constant.SP_CONFIG).put(Constant.DOWNLOAD_ID, id);
//    }

    public static void downloadAPK(String url, Context mContext) {
        //创建下载任务
        Uri uri = Uri.parse(Api.FILE_DOMAIN + url);
        DownloadManager.Request request = new DownloadManager.Request(uri);
        //移动网络情况下是否允许漫游
        request.setAllowedOverRoaming(false);
        //在通知栏中显示，默认就是显示的
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
        request.setTitle(AppUtils.getAppName());
        request.setDescription("版本更新");
        request.setVisibleInDownloadsUi(true);

        //设置下载的路径
        File file = new File(mContext.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), "projectSurvey.apk");
        request.setDestinationUri(Uri.fromFile(file));
        //获取DownloadManager
        DownloadManager downloadManager = (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);
        //将下载请求加入下载队列，加入下载队列后会给该任务返回一个long型的id，通过该id可以取消任务，重启任务、获取下载的文件等等
        long downloadId = downloadManager.enqueue(request);
        SPUtils.getInstance(Constant.SP_CONFIG).put(Constant.DOWNLOAD_ID, downloadId);

    }



    private static SimpleDateFormat DateYMDHMSS = new SimpleDateFormat("yyyyMMddHHmmssSSS");

    public static String getYMDHMSSToString(long time) {
        Date d = new Date(time);
        return DateYMDHMSS.format(d);
    }
    public static boolean StringEx(String str) {
        if("".equals(str)||str==null){
            return true;
        }else{
            return false;
        }

    }

    //删除本地照片
    public static boolean deleteLocalPicture(ContentResolver resolver, String path){
        Cursor cursor = MediaStore.Images.Media.query(resolver, MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new String[] { MediaStore.Images.Media._ID }, MediaStore.Images.Media.DATA + "=?",
                new String[] { path }, null);
        boolean result = false;
        if (cursor.moveToFirst()) {
            long id = cursor.getLong(0);
            Uri contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
            Uri uri = ContentUris.withAppendedId(contentUri, id);
            int count = resolver.delete(uri, null, null);
            result = count == 1;
        } else {
            File file = new File(path);
            result = file.delete();
        }
        return result;
    }

    /**
     * 删除单个文件
     *
     * @param fileName
     *            要删除的文件的文件名
     * @return 单个文件删除成功返回true，否则返回false
     */
    public static boolean deleteFile(String fileName) {
        File file = new File(fileName);
        // 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
        if (file.exists()) {
            if (file.delete()) {
                System.out.println("删除单个文件" + fileName + "成功！");
                return true;
            } else {
                System.out.println("删除单个文件" + fileName + "失败！");
                return false;
            }
        } else {
            System.out.println("删除单个文件失败：" + fileName + "不存在！");
            return false;
        }
    }

    public static boolean deleteLocal(File file){
        if(file.exists()){
            if(file.isFile()){
                file.delete();//如果为文件，直接删除
            }else if(file.isDirectory()){
                File []files=file.listFiles();
                for(File file1:files){
                    deleteLocal(file1);//如果为文件夹，递归调用
                }
            }
            file.delete();
            return true;
        }
        return false;
    }


    /**
     * 判断Long是否为空
     */
    public static Boolean isLongEmpty(Long number) {
        if (number == null || number == 0)
            return true;
        else
            return false;
    }

    /**
     * 判断double是否为空
     */
    public static Boolean isDoubleEmpty(Double number) {
        if (number == null || number == 0)
            return true;
        else
            return false;
    }

    /**
     * 判断float是否为空
     */
    public static Boolean isFloatEmpty(Float number) {
        if (number == null || number == 0)
            return true;
        else
            return false;
    }

    /**
     * 判断字符串是否为空
     */
    public static Boolean isStrEmpty(String str) {
        if (str == null || str.isEmpty() || str.equals("null"))
            return true;
        else
            return false;
    }

    /**
     * 判断对象是否为空
     */
    public static Boolean isObjectEmpty(Object object) {
        if (object == null || object.equals("")) {
            return true;
        } else
            return false;
    }

    /**
     * 判断数组是否为空
     */
    public static Boolean isListEmpty(List list) {
        if (list == null || list.isEmpty() || list.equals("null")
                || list.size() == 0)
            return true;
        else
            return false;
    }

    /**
     * 把bitmap转bitmap缩放处理
     */
    public static Bitmap BitmapToBitmap(Context context, Bitmap bitmap) {
        int width = 100;
        byte[] bytes = bitmap2Bytes(bitmap);
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inSampleSize = bitmap.getWidth() / width;
        bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length, options);
        return bitmap;
    }

    /**
     * bitmap转btye
     */
    public static byte[] bitmap2Bytes(Bitmap bm) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
        return baos.toByteArray();
    }

    /**
     * 将时间戳转为代表"距现在多久之前"的字符串
     *
     * @param timeStr 时间戳
     * @return
     */
    public static String getStandardDate(String timeStr) {

        StringBuffer sb = new StringBuffer();

        long t = Long.parseLong(timeStr);
        long time = System.currentTimeMillis() - (t * 1000);
        long mill = (long) Math.ceil(time / 1000);//秒前

        long minute = (long) Math.ceil(time / 60 / 1000.0f);// 分钟前

        long hour = (long) Math.ceil(time / 60 / 60 / 1000.0f);// 小时

        long day = (long) Math.ceil(time / 24 / 60 / 60 / 1000.0f);// 天前

        if (day - 1 > 0) {
            sb.append(day + "天");
        } else if (hour - 1 > 0) {
            if (hour >= 24) {
                sb.append("1天");
            } else {
                sb.append(hour + "小时");
            }
        } else if (minute - 1 > 0) {
            if (minute == 60) {
                sb.append("1小时");
            } else {
                sb.append(minute + "分钟");
            }
        } else if (mill - 1 > 0) {
            if (mill == 60) {
                sb.append("1分钟");
            } else {
                sb.append(mill + "秒");
            }
        } else {
            sb.append("刚刚");
        }
        if (!sb.toString().equals("刚刚")) {
            sb.append("前");
        }
        return sb.toString();
    }


    public static String saveBitMapToFile(Context context, String fileName, Bitmap bitmap, boolean isCover) {
        if (null == context || null == bitmap) {
            return null;
        }
        if (TextUtils.isEmpty(fileName)) {
            return null;
        }
        FileOutputStream fOut = null;
        try {
            File file = null;
            String fileDstPath = "";
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                // 保存到sd卡
                fileDstPath = Environment.getExternalStorageDirectory().getAbsolutePath()
                        + File.separator + "MyFile" + File.separator + fileName;

                File homeDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
                        + File.separator + "MyFile" + File.separator);
                if (!homeDir.exists()) {
                    homeDir.mkdirs();
                }
            } else {
                // 保存到file目录
                fileDstPath = context.getFilesDir().getAbsolutePath()
                        + File.separator + "MyFile" + File.separator + fileName;

                File homeDir = new File(context.getFilesDir().getAbsolutePath()
                        + File.separator + "MyFile" + File.separator);
                if (!homeDir.exists()) {
                    homeDir.mkdir();
                }
            }

            file = new File(fileDstPath);

            if (!file.exists() || isCover) {
                // 简单起见，先删除老文件，不管它是否存在。
                file.delete();

                fOut = new FileOutputStream(file);
                if (fileName.endsWith(".jpg")) {
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 75, fOut);
                } else {
                    bitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);
                }
                fOut.flush();
                bitmap.recycle();
            }

            Log.i("FileSave", "saveDrawableToFile " + fileName
                    + " success, save path is " + fileDstPath);
            return fileDstPath;
        } catch (Exception e) {
            Log.e("FileSave", "saveDrawableToFile: " + fileName + " , error", e);
            return null;
        } finally {
            if (null != fOut) {
                try {
                    fOut.close();
                } catch (Exception e) {
                    Log.e("FileSave", "saveDrawableToFile, close error", e);
                }
            }
        }
    }


    /*
     * 将秒数转为时分秒
     * */
    public static String Timechange(int second) {
        int h = 0;
        int d = 0;
        int s = 0;
        int temp = second % 3600;
        if (second > 3600) {
            h = second / 3600;
            if (temp != 0) {
                if (temp > 60) {
                    d = temp / 60;
                    if (temp % 60 != 0) {
                        s = temp % 60;
                    }
                } else {
                    s = temp;
                }
            }
        } else {
            d = second / 60;
            if (second % 60 != 0) {
                s = second % 60;
            }
        }

        return h + ":" + d + ":" + s + "";
    }

    /**
     * 从asset路径下读取对应文件转String输出
     *
     * @param mContext
     * @return
     */
    public static String getJson(Context mContext, String fileName) {
        // TODO Auto-generated method stub
        StringBuilder sb = new StringBuilder();
        AssetManager am = mContext.getAssets();
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(
                    am.open(fileName)));
            String next = "";
            while (null != (next = br.readLine())) {
                sb.append(next);
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            sb.delete(0, sb.length());
        }
        return sb.toString().trim();
    }

    public static String shaEncrypt(String strSrc) {
        MessageDigest md = null;
        String strDes = null;
        byte[] bt = strSrc.getBytes();
        try {
            md = MessageDigest.getInstance("SHA-256");// 将此换成SHA-1、SHA-512、SHA-384等参数
            md.update(bt);
            strDes = bytes2Hex(md.digest()); // to HexString
        } catch (NoSuchAlgorithmException e) {
            return null;
        }
        return strDes;
    }

    public static String bytes2Hex(byte[] bts) {
        String des = "";
        String tmp = null;
        for (int i = 0; i < bts.length; i++) {
            tmp = (Integer.toHexString(bts[i] & 0xFF));
            if (tmp.length() == 1) {
                des += "0";
            }
            des += tmp;
        }
        return des;
    }

    public int calculate(BitmapFactory.Options options, int width, int height) {
        int oh = options.outHeight;
        int ow = options.outWidth;
        int size;
        if (ow > oh) {
            size = width;
            width = height;
            height = size;
        }

        size = 1;
        if (ow < width && ow < height) {
            width = ow / 2;
            height = oh / 2;
        }

        if (oh > height || ow > width) {
            int rh = Math.round((float) oh / (float) height);
            int rw = Math.round((float) ow / (float) width);
            size = rh < rw ? rh : rw;
        }

        return size;
    }

    public Bitmap getSmall(String path, int width, int height) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(path, options);
        options.inSampleSize = this.calculate(options, width, height);
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeFile(path, options);
    }


    // 判断是否符合身份证号码的规范
    public static boolean isIDCard(String IDCard) {
        if (IDCard != null) {
            String IDCardRegex = "(^\\d{15}$)|(^\\d{18}$)|(^\\d{17}(\\d|X|x|Y|y)$)";
            return IDCard.matches(IDCardRegex);
        }
        return false;
    }

    public static boolean isNetworkAvailable(Context context) {

        ConnectivityManager manager = (ConnectivityManager) context
                .getApplicationContext().getSystemService(
                        Context.CONNECTIVITY_SERVICE);

        if (manager == null) {
            return false;
        }

        NetworkInfo networkinfo = manager.getActiveNetworkInfo();

        if (networkinfo == null || !networkinfo.isAvailable()) {
            return false;
        }

        return true;
    }

    public static String getNetworkType(Context context) {
        String strNetworkType = "";
        ConnectivityManager cm = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = cm.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isConnected()) {
            if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
                strNetworkType = "WIFI";
                Log.d("logger", "Network Type : " + strNetworkType);
                return strNetworkType;
            } else if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
                String _strSubTypeName = networkInfo.getSubtypeName();

                Log.e("logger", "Network getSubtypeName : " + _strSubTypeName);

                int networkType = networkInfo.getSubtype();
                switch (networkType) {
                    case TelephonyManager.NETWORK_TYPE_GPRS:
                    case TelephonyManager.NETWORK_TYPE_EDGE:
                    case TelephonyManager.NETWORK_TYPE_CDMA:
                    case TelephonyManager.NETWORK_TYPE_1xRTT:
                    case TelephonyManager.NETWORK_TYPE_IDEN: //api<8 : replace by 11
                        strNetworkType = "2G";
                        Log.e("logger", "Network Type : " + strNetworkType);
                        return strNetworkType;
                    case TelephonyManager.NETWORK_TYPE_UMTS:
                    case TelephonyManager.NETWORK_TYPE_EVDO_0:
                    case TelephonyManager.NETWORK_TYPE_EVDO_A:
                    case TelephonyManager.NETWORK_TYPE_HSDPA:
                    case TelephonyManager.NETWORK_TYPE_HSUPA:
                    case TelephonyManager.NETWORK_TYPE_HSPA:
                    case TelephonyManager.NETWORK_TYPE_EVDO_B: //api<9 : replace by 14
                    case TelephonyManager.NETWORK_TYPE_EHRPD:  //api<11 : replace by 12
                    case TelephonyManager.NETWORK_TYPE_HSPAP:  //api<13 : replace by 15
                        strNetworkType = "3G";
                        break;
                    case TelephonyManager.NETWORK_TYPE_LTE:    //api<11 : replace by 13
                        strNetworkType = "4G";
                        break;
                    default:
                        // http://baike.baidu.com/item/TD-SCDMA 中国移动 联通 电信 三种3G制式
                        if (_strSubTypeName.equalsIgnoreCase("TD-SCDMA") || _strSubTypeName.equalsIgnoreCase("WCDMA") || _strSubTypeName.equalsIgnoreCase("CDMA2000")) {
                            strNetworkType = "3G";
                        } else {
                            strNetworkType = _strSubTypeName;
                        }
                        break;
                }
                Log.e("logger", "Network getSubtype : " + Integer.valueOf(networkType).toString());
            }
        }
        Log.e("logger", "Network Type : " + strNetworkType);
        return strNetworkType;
    }

    public static int getOrderType(String t) {
        int txt = -1;
        switch (t) {
            case "全部":
                txt = -1;
                break;
            case "未支付":
                txt = 0;
                break;
            case "已支付":
                txt = 2;
                break;
            case "待付尾款":
                txt = 3;
                break;
            case "退款中":
                txt = 4;
                break;
            case "已退款":
                txt = 5;
                break;
        }
        return txt;
    }

    /**
     * 专为Android4.4设计的从Uri获取文件绝对路径，以前的方法已不好使
     */
    @SuppressLint("NewApi")
    public String getPath(final Context context, final Uri uri) {

        final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

        // DocumentProvider
        if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
            // ExternalStorageProvider
            if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }
            }
            // DownloadsProvider
            else if (isDownloadsDocument(uri)) {

                final String id = DocumentsContract.getDocumentId(uri);
                final Uri contentUri = ContentUris.withAppendedId(
                        Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

                return getDataColumn(context, contentUri, null, null);
            }
            // MediaProvider
            else if (isMediaDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }

                final String selection = "_id=?";
                final String[] selectionArgs = new String[]{split[1]};

                return getDataColumn(context, contentUri, selection, selectionArgs);
            }
        }
        // MediaStore (and general)
        else if ("content".equalsIgnoreCase(uri.getScheme())) {
            return getDataColumn(context, uri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }
        return null;
    }

    /**
     * Get the value of the data column for this Uri. This is useful for
     * MediaStore Uris, and other file-based ContentProviders.
     *
     * @param context       The context.
     * @param uri           The Uri to query.
     * @param selection     (Optional) Filter used in the query.
     * @param selectionArgs (Optional) Selection arguments used in the query.
     * @return The value of the _data column, which is typically a file path.
     */
    public String getDataColumn(Context context, Uri uri, String selection,
                                String[] selectionArgs) {

        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {column};

        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                    null);
            if (cursor != null && cursor.moveToFirst()) {
                final int column_index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(column_index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is ExternalStorageProvider.
     */
    public boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is DownloadsProvider.
     */
    public boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is MediaProvider.
     */
    public boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    public static Bitmap getVideoThumbnail(String filePath) {
        Bitmap b = null;
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        try {
            retriever.setDataSource(filePath);
            b = retriever.getFrameAtTime();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (RuntimeException e) {
            e.printStackTrace();

        } finally {
            try {
                retriever.release();
            } catch (RuntimeException e) {
                e.printStackTrace();
            }
        }
        return b;
    }

    public static Bitmap getNetVideoBitmap(String videoUrl) {
        Bitmap bitmap;

        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        //根据url获取缩略图
        retriever.setDataSource(videoUrl, new HashMap());
        //获得第一帧图片
        bitmap = retriever.getFrameAtTime();
        retriever.release();
        return bitmap;
    }

    public String getRealPathFromURI(Uri contentUri, Context context) {
        String res = null;
        String[] proj = {MediaStore.Images.Media.DATA};
        Cursor cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
        if (null != cursor && cursor.moveToFirst()) {
            ;
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            res = cursor.getString(column_index);
            cursor.close();
        }
        return res;
    }


    private static final String SD_PATH = "/sdcard/kangzhiyuan/pic/";
    private static final String IN_PATH = "/kangzhiyuan/pic/";

    /**
     * 随机生产文件名
     *
     * @return
     */
    private static String generateFileName() {
        return UUID.randomUUID().toString();
    }

    /**
     * 保存bitmap到本地
     *
     * @param context
     * @param mBitmap
     * @return
     */
    public static String saveBitmap(Context context, Bitmap mBitmap) {
        String savePath;
        File filePic;
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            savePath = SD_PATH;
        } else {
            savePath = context.getApplicationContext().getFilesDir()
                    .getAbsolutePath()
                    + IN_PATH;
        }
        try {
            filePic = new File(savePath + generateFileName() + ".jpg");
            if (!filePic.exists()) {
                filePic.getParentFile().mkdirs();
                filePic.createNewFile();
            }
            FileOutputStream fos = new FileOutputStream(filePic);
            mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        }

        return filePic.getAbsolutePath();
    }


    /**
     * 自定义自动换行 TV CHECKBOX通用
     *
     * @param context
     * @param mBitmap
     * @return
     */
    public String getAutoStringLine(String str){

        if (str.length()>25){
            int x=str.indexOf('《');
            int y=str.indexOf('》');
            int z=str.length();
            String a=str.substring(0,y+1);
            String b=str.substring(y+1,z);
            str=a+"\n"+b;
        }
        return  str;
    }


    public static String md5Password(String password){
        StringBuffer sb = new StringBuffer();
        // 得到一个信息摘要器
        try {
            MessageDigest digest = MessageDigest.getInstance("md5");
            byte[] result = digest.digest(password.getBytes());
            // 把每一个byte做一个与运算 0xff
            for (byte b : result) {
                // 与运算
                int number = b & 0xff;
                String str = Integer.toHexString(number);
                if (str.length() == 1) {
                    sb.append("0");
                }
                sb.append(str);
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }


    public static boolean hasSdcard() {
         String status = Environment.getExternalStorageState();
       if (status.equals(Environment.MEDIA_MOUNTED)) {
                return true;
           } else {
                return false;
               }
        }

        /**
         *
         * */
        public static void createPath(String path) {

            File file = new File(path);
            if (!file.exists())
            {
                System.out.println("path++++========================开始创建 path="+path);
                file.mkdir();
            }
        }

         public static String getSDPath() {
            File sdDir = null;
            boolean sdCardExist;// 判断sd卡是否存在
                if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
                    sdCardExist = true;
                    else sdCardExist = false;
                if (sdCardExist) {
                    sdDir = Environment.getExternalStorageDirectory();// 获取跟目录
                }
                return sdDir.toString();
        }


    public static boolean fileIsExists(String filePath)
    {
        try
        {
            File f = new File(filePath);
            if(!f.exists())
            {
                return false;
            }
        }
        catch (Exception e)
        {
            return false;
        }
        return true;
    }


}
